package com.wenxixuanwu.fruitstore.service.impl;

import com.wenxixuanwu.fruitstore.entity.CartVO;
import com.wenxixuanwu.fruitstore.entity.OrderItem;
import com.wenxixuanwu.fruitstore.entity.OrderList;
import com.wenxixuanwu.fruitstore.entity.User;
import com.wenxixuanwu.fruitstore.mapper.OrderMapper;
import com.wenxixuanwu.fruitstore.service.CartService;
import com.wenxixuanwu.fruitstore.service.OrderService;
import com.wenxixuanwu.fruitstore.service.exception.ProductNotFundException;
import com.wenxixuanwu.fruitstore.util.GenerateNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author :小凡凡
 * @version :1.0
 * @Project :fruitstore
 * @Date :2022/5/11
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartService cartService;

    @Override
    @Transactional
    public OrderList create(Integer[] cids, HttpSession session) {
        User user = (User)session.getAttribute("u");
        //根据查询勾选的购物车列表找中的数据
        List<CartVO> carts = cartService.getVOByCid(cids, session);
        double totalPrice = 0.0;//计算商品的总价
        for (CartVO cart : carts){
            totalPrice += cart.getPrice() * cart.getNum();
        }
        OrderList order = new OrderList();
        order.setOId(GenerateNum.getInstance().GenerateOrder());
        order.setUserId(user.getId());
        order.setAddress(user.getAddress());
        order.setCreated(new Date());
        order.setState(0);
        order.setPriceAll(totalPrice);
        order.setFruitId(0);
        order.setTypeId(0);
        Integer rows1 = orderMapper.insertOrder(order);
        if (rows1 != 1){
            throw new ProductNotFundException("插入订单时数据不正确！");
        }

        for (CartVO cart : carts){
            OrderItem item = new OrderItem();
            item.setOid(order.getOId());
            item.setPid(cart.getPid());
            item.setPname(cart.getName());
            item.setPurl(cart.getUrl());
            item.setPrice(cart.getPrice());
            item.setNum(cart.getNum());
            Integer rows2 = orderMapper.insertOrderItem(item);
            if (rows2 != 1){
                throw  new ProductNotFundException("插入订单项数据出现错误！");
            }
        }
        return order;
    }
}
